package com.sayice.gomoku.web;

import com.sayice.gomoku.pojo.Admin;
import com.sayice.gomoku.pojo.BoardInfo;
import com.sayice.gomoku.service.AdminService;
import com.sayice.gomoku.service.BoardService;
import com.sayice.gomoku.service.impl.AdminServiceImpl;
import com.sayice.gomoku.service.impl.BoardServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

/**
 * 处理管理员业务请求
 */
@WebServlet(urlPatterns = "/adminServlet")
public class AdminServlet extends BaseServlet {
    private final AdminService adminService = new AdminServiceImpl();
    private final BoardService boardService = new BoardServiceImpl();
    
    /**
     * 登录
     */
    protected void login(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String name = req.getParameter("name").trim();
        String password = req.getParameter("password").trim();
        Admin admin = new Admin();
        admin.setName(name);
        admin.setPassword(password);
        Admin loginAdmin = adminService.login(admin);
        if (loginAdmin == null) {
            req.setAttribute("msg", "用户名或密码错误！");
            req.setAttribute("name", name);
            req.getRequestDispatcher("/pages/admin/login.jsp").forward(req, resp);
            return;
        }
        System.out.println("管理员登录成功");
        List<BoardInfo> boardInfos = boardService.getBoardInfos();
        req.setAttribute("adminId", loginAdmin.getId());
        req.setAttribute("boardInfos", boardInfos);
        req.getRequestDispatcher("/pages/manager/board.jsp").forward(req, resp);
    }
    
    /**
     * 退出登录
     */
    protected void logout(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException {
        req.removeAttribute("admin");
        req.getRequestDispatcher("/pages/admin/login.jsp").forward(req, resp);
    }
}
